package com.cloud.user_info.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.common.domain.Result;
import com.cloud.entity.SysDept;
import com.cloud.entity.SysDeptArea;
import com.cloud.entity.SysRole;
import com.cloud.common.enums.CheckType;
import com.cloud.common.enums.DeptType;
import com.cloud.exception.CustomException;
import com.cloud.scope.DataScope;
import com.cloud.user_info.mapper.SysDeptAreaMapper;
import com.cloud.user_info.mapper.SysDeptMapper;
import com.cloud.user_info.mapper.SysRoleMapper;
import com.cloud.user_info.service.ISysDeptService;
import com.cloud.utils.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门管理 服务实现
 *
 * @author hhb, yzj
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    @Resource
    private SysDeptMapper deptMapper;

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysDeptAreaMapper sysDeptAreaMapper;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept) {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 根据ID查询子级部门主键列表
     *
     * @param deptId 部门ID
     * @return 部门id集合
     */
    @Override
    public List<Long> selectChildDeptId(Long deptId) {
        return deptMapper.selectChildDeptId(deptId);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        for (SysDept dept : depts) {
            tempList.add(dept.getDeptId());
        }
        for (SysDept dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param dept 部门信息
     * @return 下拉树结构列表
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> buildDeptTreeSelect(SysDept dept) {
        List<SysDept> deptList = deptMapper.selectDeptList(dept);
        return buildDeptTree(deptList);
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> selectDeptListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept) {
        int count = deptMapper.checkDeptNameUnique(dept);
        if (count > 0) {
            return CheckType.NOT_UNIQUE.getCode();
        }
        return CheckType.UNIQUE.getCode();
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public Result insertDept(SysDept dept) {
        SysDept sysDept = deptMapper.selectDeptById(dept.getParentId());
        // TODO 如果父节点不为正常状态,则不允许新增子节点
        if (StringUtils.isNull(sysDept) || !DeptType.DEPT_NORMAL.getCode().equals(sysDept.getStatus())) {
            throw new CustomException("部门已停用,不允许新增");
        }
        SysDeptArea sysDeptArea = null;
        if (DeptType.IS_AREA.getCode().equals(dept.getNodeType()) || StringUtils.isNotNull(dept.getAreaCode())) {
            int codeRows = sysDeptAreaMapper.checkAreaCodeUnique(dept.getAreaCode());
            if (codeRows > 0) {
                return Result.error("操作失败:区域编号重复");
            }
            sysDeptArea = new SysDeptArea();
            sysDeptArea.setAreaCode(dept.getAreaCode());
            sysDeptArea.setParentId(dept.getAreaParentId());
            sysDeptArea.setAreaName(dept.getAreaName());
            sysDeptArea.setUserId(dept.getLeaderId());
        }
        dept.setAncestors(sysDept.getAncestors() + "," + dept.getParentId());
        deptMapper.insert(dept);
        if (StringUtils.isNotNull(sysDeptArea)) {
            sysDeptArea.setDeptId(dept.getDeptId());
            // 添加部门区域信息
            sysDeptAreaMapper.insert(sysDeptArea);
        }
        return Result.success("操作成功");
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public Result updateDept(SysDept dept) {
        SysDeptArea sysDeptArea = null;
        if (DeptType.IS_AREA.getCode().equals(dept.getNodeType()) || StringUtils.isNotNull(dept.getAreaCode())) {
            SysDeptArea deptAreaInfo = sysDeptAreaMapper.selectDeptAreaByCode(dept.getAreaCode());
            if (StringUtils.isNotNull(deptAreaInfo)) {
                if (!dept.getAreaCode().equals(deptAreaInfo.getAreaCode())) {
                    return Result.error("操作失败:区域编号已存在");
                }
            }
            sysDeptArea = new SysDeptArea();
            sysDeptArea.setDeptId(dept.getDeptId());
            sysDeptArea.setAreaCode(dept.getAreaCode());
            sysDeptArea.setParentId(dept.getAreaParentId());
            sysDeptArea.setAreaName(dept.getAreaName());
            sysDeptArea.setUserId(dept.getLeaderId());
        }
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        deptMapper.updateById(dept);
        if (Integer.valueOf(DeptType.DEPT_NORMAL.getCode()).equals(dept.getStatus())) {
            // TODO 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
        if (StringUtils.isNotNull(sysDeptArea)) {
            int rows = sysDeptAreaMapper.checkAreaDeptUnique(dept.getDeptId());
            if (rows > 0) {
                UpdateWrapper<SysDeptArea> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("dept_id", dept.getDeptId());
                // 修改部门区域信息
                sysDeptAreaMapper.update(sysDeptArea, updateWrapper);
            } else {
                sysDeptAreaMapper.insert(sysDeptArea);
            }
        }
        return Result.success("操作成功");
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept) {
        String updateBy = dept.getUpdateBy();
        dept = deptMapper.selectDeptById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        deptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    @Transactional
    public Result deleteDeptById(Long deptId) {
        // 根据部门id删除部门区域信息
        sysDeptAreaMapper.deleteAreaByDeptId(deptId);
        // 根据部门id删除部门信息
        deptMapper.deleteById(deptId);
        return Result.success("操作成功");
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<>();
        for (SysDept dept : list) {
            if (StringUtils.isNotNull(dept.getParentId()) && dept.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(dept);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 查询部门级节点
     *
     * @param sysDept
     * @return
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptByLower(SysDept sysDept) {
        return deptMapper.selectDeptByLower(sysDept);
    }

    /**
     * 根据部门ID查询上级区域信息
     *
     * @param deptId
     * @return
     */
    @Override
    public SysDeptArea getSuperAreaDept(Long deptId) {
        SysDeptArea deptArea = null;
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        if (StringUtils.isNotNull(sysDept) && 0 != sysDept.getParentId()) {
            // 判断该节点是否是区域，否则回调查询父级节点信息
            if (DeptType.IS_AREA.getCode().equals(sysDept.getNodeType())) {
                deptArea = sysDeptAreaMapper.selectAreaDeptById(sysDept.getDeptId());
                return deptArea;
            } else {
                return getSuperAreaDept(sysDept.getParentId());
            }
        } else {
            return deptArea;
        }
    }

    /**
     * 查询角色部门数据权限
     *
     * @param roleId
     * @return
     */
    @Override
    public String selectDeptScopeByRoleId(Long roleId) {
        String result = null;
        List<String> list = deptMapper.selectDeptScopeByRoleId(roleId);
        if (list.size() > 0) {
            result = list.stream().map(String::valueOf).collect(Collectors.joining(","));
        }
        return result;
    }

    /**
     * 查询部门以下数据权限
     *
     * @param deptId
     * @return
     */
    @Override
    public String selectDeptAfterScope(Long deptId) {
        String result = null;
        List<String> list = deptMapper.selectDeptAfterScope(deptId);
        if (list.size() > 0) {
            result = list.stream().map(String::valueOf).collect(Collectors.joining(","));
        }
        return result;
    }

    /**
     * 根据部门全称查询部门对象
     *
     * @param deptName
     * @return
     */
    @Override
    public SysDept selectDeptByName(String deptName) {
        return deptMapper.selectDeptByName(deptName);
    }

    /**
     * 根据部门id查询部门对象
     *
     * @param deptId
     * @return
     */
    @Override
    public SysDept getInDeptByDeptId(Long deptId) {
        return deptMapper.getInDeptByDeptId(deptId);
    }

    /**
     * 根据部门id查询用户id
     */
    @Override
    public List<Long> getDeptUserIdsById(String deptIds) {
        return deptMapper.getDeptUserIdsById(deptIds);
    }

}
